package com.momo.service.authority;

import com.google.common.collect.Lists;
import com.momo.common.req.sysmain.RedisUser;
import com.momo.common.res.authority.LoginAuthReq;
import com.momo.mapper.dataobject.AclDO;
import com.momo.mapper.mapper.sysSetting.AuthorityMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Kagome on 2019/3/23.
 * 本部 权限 核心
 */
@Service
public class AdminSysCoreService {

    @Value("${momo.isSuperAdmin}")
    private String isSuperAdmin;
    @Autowired
    private AuthorityMapper authorityMapper;

    public List<AclDO> getRoleAclList(Long roleId) {
        List<Long> aclIdList = authorityMapper.aclsByRoleId(Lists.<Long>newArrayList(roleId));
        if (CollectionUtils.isEmpty(aclIdList)) {
            return Lists.newArrayList();
        }
        return authorityMapper.getAllAcl(null,aclIdList);
    }

    public List<AclDO> getUserAclList(LoginAuthReq loginAuthReq, RedisUser redisUser) {
        if (isSuperAdmin(redisUser)) {
            return authorityMapper.getAllAcl(loginAuthReq.getAclPermissionType(), null);
        }
        List<Long> userRoleIdList = authorityMapper.rolesByUserId(redisUser.getId());
        if (CollectionUtils.isEmpty(userRoleIdList)) {
            return Lists.newArrayList();
        }
        List<Long> userAclIdList = authorityMapper.aclsByRoleId(userRoleIdList);
        if (CollectionUtils.isEmpty(userAclIdList)) {
            return Lists.newArrayList();
        }
        return authorityMapper.getAllAcl(loginAuthReq.getAclPermissionType(), userAclIdList);
    }

    public boolean isSuperAdmin(RedisUser redisUser) {
        // 这里是我自己定义了一个假的超级管理员规则，实际中要根据项目进行修改
        // 可以是配置文件获取，可以指定某个用户，也可以指定某个角色
        if (isSuperAdmin.trim().equals(redisUser.getSysUserPhone())) {
            return true;
        }
        return false;
    }
}
